<template>
    <v-data-table
            :headers="headers"
            :items="desserts"
            :search="search"
            :items-per-page="-1"
            :footer-props="footer"
            class="elevation-1"
    >
        <template v-slot:top>
            <v-toolbar flat color="white">
                <v-toolbar-title>{{ title }}</v-toolbar-title>
                <v-divider class="mx-4" inset vertical></v-divider>
                <v-dialog v-model="dialog" max-width="500px">
                    <template v-slot:activator="{ on, attrs }">
                        <v-icon color="primary" v-bind="attrs" v-on="on">mdi-database-plus</v-icon>
                    </template>
                    <v-card>
                        <v-card-title>
                            <span class="headline">{{ formTitle }}</span>
                        </v-card-title>

                        <v-card-text>
                            <v-container>
                                <v-row>
                                    <!-- 仿写下面的col -->
                                    <v-col cols="12" sm="12" md="6">
                                        <v-select
                                                v-model="editedItem.parentId"
                                                :items="options"
                                                label="父节点"
                                        ></v-select>
                                    </v-col>
                                    <v-col cols="12" sm="12" md="6">
                                        <v-text-field
                                                v-model="editedItem.meta.name"
                                                label="名称"
                                                hint="设置菜单英文名,首字母大写"
                                                append-icon="mdi-sync"
                                                @click:append="autoset"
                                        ></v-text-field>
                                    </v-col>
                                    <v-col cols="12" sm="12" md="6">
                                        <v-text-field
                                                v-model="editedItem.meta.title"
                                                label="标题"
                                                hint="设置菜单标题，左侧导航栏展示"
                                        ></v-text-field>
                                    </v-col>
                                    <v-col cols="12" sm="12" md="6">
                                        <v-text-field
                                                v-model="editedItem.path"
                                                label="路径"
                                                hint="指定一个路径，路由访问地址"
                                        ></v-text-field>
                                    </v-col>
                                    <v-col cols="12" sm="12" md="6">
                                        <v-text-field
                                                v-model="editedItem.meta.icon"
                                                label="图标"
                                                hint="指定一个图标"
                                                prefix="mdi-"
                                                :append-icon="'mdi-'+editedItem.meta.icon"
                                        ></v-text-field>
                                    </v-col>
                                    <v-col cols="12" sm="12" md="6">
                                        <v-text-field
                                                v-model="editedItem.component"
                                                label="视图"
                                                hint="指定视图文件路径"
                                        ></v-text-field>
                                    </v-col>
                                </v-row>
                            </v-container>
                        </v-card-text>
                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn color="error" text @click="close">Cancel</v-btn>
                            <v-btn color="success" text @click="save">Save</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
                <v-spacer></v-spacer>
                <v-text-field
                        v-model="search"
                        append-icon="mdi-magnify"
                        label="Search"
                        single-line
                        hide-details
                ></v-text-field>
            </v-toolbar>
        </template>
        <template v-slot:item.meta.title="{ item }">
            <v-icon color="accent">mdi-{{ item.meta.icon }}
            </v-icon
            >
            {{ item.meta.title }}
        </template>
        <template v-slot:item.actions="{ item }">
            <v-icon color="primary" class="mr-2" @click="editItem(item)">
                mdi-pencil
            </v-icon>
            <v-icon color="warning" @click="deleteItem(item)"> mdi-delete</v-icon>
        </template>
        <template v-slot:no-data>
            <v-btn color="primary" @click="initialize">Reset</v-btn>
        </template>
    </v-data-table>
</template>

<script>
    // 引用各自的API
    import {GetListMenu, CreateOneMenu, UpdateOneMenu, RemoveOneMenu} from "@/api/menu.js";
    import {mapGetters} from "vuex";

    export default {
        data: () => ({
            dialog: false,
            search: "",
            desserts: [],
            editedIndex: -1,
            options: [],
            // Todo 修改下面三个字段
            // ============================================================================
            title: "菜单",
            headers: [
                //   这里写列信息
                {text: "名称", value: "meta.name", sortable: false},
                {text: "标题", value: "meta.title", sortable: false},
                {text: "路径", value: "path", sortable: false},
                {text: "Actions", value: "actions", sortable: false},
            ],
            editedItem: {
                path: "",
                parentId: 0,
                meta: {
                    name: "",
                    title: "",
                    icon: "home",
                },
            },
            defaultItem: {
                path: "",
                parentId: 0,
                meta: {
                    name: "",
                    title: "",
                    icon: "home",
                },
            },

            // ============================================================================
        }),
        computed: {
            ...mapGetters("app", ["isMobile", "footer"]),
            ...mapGetters(["role"]),
            formTitle() {
                return this.editedIndex === -1
                    ? "新建" + this.title
                    : "更新" + this.title;
            },
            parents() {
                const res = this.desserts
                    .filter((menu) => {
                        return menu.parentId === 0;
                    })
                    .map((menu) => {
                        return {
                            value: menu.id,
                            text: menu.meta.name,
                        };
                    });
                res.unshift({
                    value: 0,
                    text: "Root",
                });
                return res;
            },
        },

        watch: {
            dialog(val) {
                val || this.close();
            },
        },

        created() {
            this.refresh();
            // 由于this.options 依赖 this.desserts，所有交换两个函数顺序
            this.initialize();
        },

        methods: {
            initialize() {
                // console.log("什么也没发生");
            },
            refresh() {
                // Todo 这里从后台请求数据，写入this.desserts
                GetListMenu().then((res) => {
                    this.desserts = res.body;
                    // Todo 如果Dialog中设计Select,请在此处初始化this.options
                    this.options = this.desserts
                        .filter((menu) => {
                            return menu.parentId === 0;
                        })
                        .map((menu) => {
                            return {
                                value: menu.id,
                                text: menu.meta.name,
                            };
                        });
                    this.options.unshift({
                        value: 0,
                        text: "Root",
                    });
                });

            },

            editItem(item) {
                this.editedIndex = this.desserts.indexOf(item);

                // Object.assign()拷贝
                // 当对象中只有一级属性，没有二级属性的时候，此方法为深拷贝，但是对象中有对象的时候，此方法，在二级属性以后就是浅拷贝。
                this.editedItem = Object.assign({}, item);
                this.editedItem.meta = Object.assign({}, item.meta); // 增加一个修正
                this.dialog = true;
            },

            close() {
                this.dialog = false;
                this.$nextTick(() => {
                    this.editedItem = Object.assign({}, this.defaultItem);
                    this.editedIndex = -1;
                });
            },

            //  下面两个方法需要增加相应的后台交互操作
            save() {
                if (this.editedIndex > -1) {
                    //   update
                    // Object.assign(this.desserts[this.editedIndex], this.editedItem);
                    UpdateOneMenu(this.editedItem).then(res => {
                        this.$msg.info(res.msg);
                        this.refresh()
                    }).catch(res => {
                        this.$msg.error(res.msg)
                    })
                } else {
                    //   create
                    // this.desserts.push(this.editedItem);
                    CreateOneMenu(this.editedItem).then(res => {
                        this.$msg.info(res.msg)
                        this.refresh()
                    })
                }
                this.close();
            },
            deleteItem(item) {
                // const index = this.desserts.indexOf(item);
                confirm("确认删除?") &&
                // this.desserts.splice(index, 1);
                RemoveOneMenu(item.id).then(res => {
                    this.$msg.info(res.msg)
                    this.refresh()
                }, err => {
                    // this.$msg.error(err.data.msg)
                    console.debug(err)
                })
            },
            autoset() {
                let str = this.editedItem.meta.name.toLowerCase()
                this.editedItem.path = "/" + str
                this.editedItem.component = str
                this.editedItem.meta.name = str.slice(0, 1).toUpperCase() + str.slice(1)
            }
        },
    };
</script>